package com.wdd.atcrowdfunding.manager.controller;

import com.wdd.atcrowdfunding.bean.Advertisement;
import com.wdd.atcrowdfunding.bean.User;
import com.wdd.atcrowdfunding.manager.service.AdvertisementService;
import com.wdd.atcrowdfunding.util.AjaxResult;
import com.wdd.atcrowdfunding.util.Const;
import com.wdd.atcrowdfunding.util.Page;
import com.wdd.atcrowdfunding.util.StringUtil;
import com.wdd.atcrowdfunding.vo.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/advert")
public class AdevertController {


    @Autowired
    private AdvertisementService advertisementService;


    @RequestMapping("/index")
    public String index() {
        return "advert/index";
    }

    @RequestMapping("/add")
    public String add() {
        return "advert/add";
    }

	@RequestMapping("/edit")
	public String edit( Integer id, Model model ) {

		// 根据主键查询资质信息
		Advertisement advertisement = advertisementService.queryById(id);
		model.addAttribute("advert", advertisement);

		return "advert/edit";
	}

	@ResponseBody
	@RequestMapping("/update")
	public AjaxResult update(Advertisement advertisement ) {
		AjaxResult ajaxResult = new AjaxResult();

		//创建日期
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		advertisement.setCreatetime(dateString);

		try {
			int count = advertisementService.updateAdvert(advertisement);
			if ( count == 1 ) {
				ajaxResult.setSuccess(true);
			} else {
				ajaxResult.setSuccess(false);
			}
		} catch ( Exception e ) {
			e.printStackTrace();
			ajaxResult.setSuccess(false);
		}

		return ajaxResult;
	}



	/**
	 * 添加广告
	 * @param request
	 * @param advertisement
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public AjaxResult doAdd(HttpServletRequest request, Advertisement advertisement , HttpSession session) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)request;

			MultipartFile mfile = mreq.getFile("advpic"); // 临时目录

			String name = mfile.getOriginalFilename();//java.jpg
			String extname = name.substring(name.lastIndexOf(".")); // .jpg

			String iconpath = UUID.randomUUID().toString()+extname; //  232243343.jpg

			ServletContext servletContext = session.getServletContext();
			String realpath = servletContext.getRealPath("/pics");

			String path =realpath+ "\\adv\\"+iconpath;  // 真实目录

			mfile.transferTo(new File(path)); //文件上传.

			User user = (User)session.getAttribute(Const.LOGIN_USER);
            advertisement.setUserid(user.getId());
            advertisement.setStatus("0");
            advertisement.setIconpath(iconpath);

			//创建日期
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = formatter.format(currentTime);
			advertisement.setCreatetime(dateString);

			int count = advertisementService.insertAdvertisement(advertisement);
			ajaxResult.setSuccess(count==1);
		} catch ( Exception e ) {
			e.printStackTrace();
			ajaxResult.setSuccess(false);
		}

		return ajaxResult;
	}


	/**
	 * 页面异步显示
	 * @param pagetext
	 * @param pageno
	 * @param pagesize
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/doIndex")
	public AjaxResult doIndex(String pagetext, Integer pageno, Integer pagesize) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			// 查询资质数据
			Map<String, Object> advertMap = new HashMap<String, Object>();
			advertMap.put("pageno", pageno);
			advertMap.put("pagesize", pagesize);
			if ( StringUtil.isNotEmpty(pagetext) ) {
				pagetext = pagetext.replaceAll("%", "\\\\%");
			}
			if ( StringUtil.isNotEmpty(pagetext) ) {
				pagetext = pagetext.replaceAll("_", "\\\\_");
			}
			advertMap.put("pagetext", pagetext);

			// 分页查询
			Page<Advertisement> page = advertisementService.pageQuery(advertMap);
			ajaxResult.setPage(page);
			ajaxResult.setSuccess(true);
		} catch ( Exception e ) {
			e.printStackTrace();
			ajaxResult.setSuccess(false);
		}

		return ajaxResult;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public AjaxResult delete(Integer id,HttpSession session){
		AjaxResult ajaxResult = new AjaxResult();
		try{
			Advertisement advertisement = advertisementService.selectAdvert(id);
			int count = advertisementService.delete(id);
			if(count==1 && advertisement!=null){
				ajaxResult.setSuccess(true);

				ServletContext servletContext = session.getServletContext();
				String realpath = servletContext.getRealPath("/pics");
				String path =realpath+ "\\adv\\"+advertisement.getIconpath();  // 真实目录
				File file = new File(path);
				file.delete();
			}

		}catch (Exception e){
			ajaxResult.setSuccess(false);

		}
		return ajaxResult;
	}


	@ResponseBody
	@RequestMapping("/batchDelete")
	public Object batchDelete(Data ds,HttpSession session) {
		AjaxResult result = new AjaxResult();

		try {
			List<Advertisement> advertisements = advertisementService.selectAdvertsByVo(ds);
			int count = advertisementService.deleteAdverts(ds);
			if ( count == ds.getDatas().size() ) {
				result.setSuccess(true);

				ServletContext servletContext = session.getServletContext();
				String realpath = servletContext.getRealPath("/pics");
				for(Advertisement advert : advertisements ){
					String path =realpath+ "\\adv\\"+advert.getIconpath();  // 真实目录
					File file = new File(path);
					file.delete();
				}

			} else {
				result.setSuccess(false);
			}
		} catch ( Exception e ) {
			e.printStackTrace();
			result.setSuccess(false);
		}

		return result;
	}
}
